//
//  MTAddFriendViewController.swift
//  MT
//
//  Created by ooops on 2020/2/22.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import GrowingTextView
import MTCategory
import YPNavigationBarTransition

extension MTAddFriendViewController: MTAddFriendNumberViewDelegate {
    func numberButtonResult(_ numberButton: MTAddFriendNumberView, number: String) {
        if let count = Int(number) {
            if count >= numberButton.maxValue {
                MBProgressHUD_JChat.show(text: "已达最大礼物数量", view: self.view, 1.5)
                numberButton.textField.text = "\(numberButton.maxValue)"
            } else if count <= numberButton.minValue {
                numberButton.textField.text = "\(numberButton.minValue)"
                MBProgressHUD_JChat.show(text: "礼物数量不能小于\(numberButton.minValue)", view: self.view, 1.5)
            }
            if let price = self.giftModel.price {
                mtArrtibute(text: "\(count * price )")
            }
        } else {
            mtArrtibute(text: "0")
        }
    }
}

class MTAddFriendViewController: BaseViewController {
    
    //var user: JMSGUser?
    var userName: String?
    var nickName: String?
    var giftCount: Int = 1
    private var giftModel: MiTuGiftModel!
    
    /// MTProvider
    fileprivate lazy var provider: MTProvider<MiTuGiftApi> = {
        return MTProvider<MiTuGiftApi>(plugins: [])
    }()
    
    private let clubProvider: MTProvider = MTProvider<MTClubApi>()
    
    convenience init(giftCount: Int = 1, targetUserName: String?, giftModel: MiTuGiftModel) {
        self.init()
        self.userName = targetUserName
        self.giftCount = giftCount
        self.giftModel = giftModel
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "好友申请验证"
        setupUI()
        makeConstraint()
        //
        let u = JMSGUser.myInfo().displayName()
        invitationMessageView.text = "我是\(u)"
        
        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.text.x9b9b9b, NSAttributedString.Key.font:PingFangSCSemiboldFont(16)]
        if let price = self.giftModel.price {
            mtArrtibute(text: "\(self.giftCount * price)")
        }
    }
    
    private func setupUI() {
        view.addSubview(tipsLabel)
        view.addSubview(invitationMessageView)
        
        view.addSubview(giftCountLabel)
        view.addSubview(numberView)
        
        view.addSubview(lineView)
        view.addSubview(bottomLabel)
        bottomLabel.addSubview(sendGiftButton)
        
    }
    
    private func makeConstraint() {
        tipsLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(NavigationBarHeight + StatusBarHeight + 10)
        }
        
        invitationMessageView.snp.makeConstraints { (make) in
            make.top.equalTo(tipsLabel.snp.bottom).offset(9)
            make.left.equalTo(tipsLabel)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(106)
            make.centerX.equalToSuperview()
        }
        
        giftCountLabel.snp.makeConstraints { (make) in
            make.top.equalTo(invitationMessageView.snp.bottom).offset(50)
            make.left.equalTo(invitationMessageView)
        }
        
        numberView.snp.makeConstraints { (make) in
            make.centerY.equalTo(giftCountLabel)
            make.right.equalTo(invitationMessageView)
            make.width.equalTo(180)
            make.height.equalTo(30)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.top.equalTo(giftCountLabel.snp.bottom).offset(18)
            make.left.right.equalTo(invitationMessageView)
            make.height.equalTo(1)
        }
        
        bottomLabel.snp.makeConstraints { (make) in
            make.top.equalTo(lineView.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
            make.height.equalTo(50)
            make.width.equalTo(332)
        }
        
        sendGiftButton.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
    }
    
    lazy var tipsLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCRegularFont(12)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "来一句与众不同的搭讪"
        return l
    }()
    
    lazy var invitationMessageView: GrowingTextView = {
        let textView = GrowingTextView()
        textView.frame = CGRect(x: 54, y: 190, width: 300, height: 100)
        textView.layer.cornerRadius = 3.0
        textView.placeholder = ""
        textView.font = PingFangSCRegularFont(16)
        textView.maxLength = 50
        //textView.delegate = self
        textView.minHeight = 100
        textView.placeholder = "我是张三，很高兴遇见你…"
        textView.maxHeight = 100
        textView.backgroundColor = .white
        textView.layer.borderColor = UIColor(hex: 0xd8d8d8).cgColor
        textView.layer.borderWidth = 1
        return textView
    }()
    
    lazy var giftCountLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "选择赠送的礼物数量"
        return l
    }()
    
    lazy var numberView: MTAddFriendNumberView = {
        let v = MTAddFriendNumberView()
        v.setImage(decreaseImage: UIImage(named: "icon_gift_reduce")!, increaseImage: UIImage(named: "icon_gift_plus")!)
        v.textField.backgroundColor = .white
        v.textField.layer.borderColor = UIColor(hex: 0xd8d8d8).cgColor
        v.textField.layer.borderWidth = 1
        v.textField.layer.cornerRadius = 4
        v.textField.layer.masksToBounds = true
        v.shakeAnimation = true
        v.maxValue = 1000000
        v.delegate = self
        v.textField.endEditing(true)
        return v
    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0xd8d8d8)
        return v
    }()
    
    lazy var bottomLabel: UILabel = {
        let v = UILabel()
        v.layer.cornerRadius = 25
        v.layer.masksToBounds = true
        v.backgroundColor = UIColor(hex: 0xffc000)
        v.textAlignment = .center
        v.isUserInteractionEnabled = true
        return v
    }()
    
    lazy var sendGiftButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(MTAddFriendViewController.sendGift), for: .touchUpInside)
        btn.backgroundColor = .clear
        return btn
    }()
    
    private func mtArrtibute(text: String) {
        
        let markAttribute_f = NSMutableAttributedString(string: "需要消耗")
        
        let markAttribute = NSMutableAttributedString(string: text)
        
        let arrtibuteValue: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor : UIColor.text.x1d1a1a,
                                                             NSAttributedString.Key.font : PingFangSCMediumFont(16)]
        
        markAttribute.addAttributes(arrtibuteValue, range: NSRange(location: 0, length: text.count))
        
        let markattch = NSTextAttachment()
        
        markattch.image = UIImage(named: "icon_send_gift_dimond")
        
        markattch.bounds = CGRect(x: 0, y: -2, width: 20, height: 16)
        
        let markattchStr = NSMutableAttributedString(attachment: markattch)
        
        markattchStr.append(markAttribute)
        
        markAttribute_f.append(markattchStr)
        
        self.bottomLabel.attributedText = markAttribute_f
    
    }
    
    @objc private func sendGift() {
        guard let count: Int = Int(numberView.textField.text!) else { return }
        guard let price = giftModel.price else { return }
        MBProgressHUD_JChat.showLoading(self.view)
        /// 查询创建俱乐部所需要消耗的钻石
        MTClubTool.config(provider: clubProvider, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            MBProgressHUD_JChat.dismiss(weakSelf.view)
            let amount = price * count
            guard let ticketAmount = model?.result?.ticketAmount else { return }
            if model?.code == 200, price * count > ticketAmount {
                UIAlertController.rx.show(in: weakSelf, title: "余额不足", message: "此次将花费\(amount)钻石", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
                    /// 去充值的引导
                    if index == 1 {
                        if UserDefaults.AppValidate.isValidate.storedBool == false {
                            let c = MTPaymentViewController()
                            weakSelf.navigationController?.pushViewController(c, animated: true)
                        } else {
                            let c = MTInAppPurchasesViewController()
                            weakSelf.navigationController?.pushViewController(c, animated: true)
                        }
                    }
                })
                .disposed(by: globalDisposedBag)
                return
            } else {
                weakSelf._sendGift(count: count)
            }
        }) { [weak self] (error) in
            guard let weakSelf = self else { return }
            MBProgressHUD_JChat.show(text: "网络异常", view: weakSelf.view)
            MBProgressHUD_JChat.dismiss(weakSelf.view)
            return
        }
    }
    
    private func _sendGift(count: Int) {
        guard let userName = self.userName else { return }
        let requestParam: [String : Any] = ["count": count,
                                            "giftId": giftModel.id!,
                                            "message": self.invitationMessageView.text ?? "",
                                            "userName": userName]
        
        provider.originRequest(.sendGift(requestParam), callbackQueue: .main, progress: nil) { [weak self] (result, _) in
            guard let weakSelf = self else { return }
            MBProgressHUD_JChat.dismiss(weakSelf.view)
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    
                    if code == 200 {
                        if let result = datas["result"] as? [String: Any] {
                            UserCenter.default.set(with: result)
                        }
                        weakSelf._addFriend()
                        DispatchQueue.main.async {
                            MBProgressHUD_JChat.show(text: "好友请求已发送", view: weakSelf.view, 1)
                            DispatchQueue.main.after(1.1) {
                                weakSelf.navigationController?.popToRootViewController(animated: false)
                            }
                        }
                    } else if code == 600 {
                        // 600 余额不做
                        UIAlertController.rx.show(in: weakSelf, title: "余额不足", message: "是否进行充值", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
                            /// 去充值的引导
                            if index == 1 {
                                if UserDefaults.AppValidate.isValidate.storedBool == false {
                                    let c = MTPaymentViewController()
                                    weakSelf.navigationController?.pushViewController(c, animated: true)
                                } else {
                                    let c = MTInAppPurchasesViewController()
                                    weakSelf.navigationController?.pushViewController(c, animated: true)
                                }
                            }
                        }).disposed(by: globalDisposedBag)
                    } else {
                        DispatchQueue.main.async {
                            MBProgressHUD_JChat.show(text: "好友请求发送失败", view: weakSelf.view, 1)
                        }
                    }
                } else {
                    DispatchQueue.main.async {
                        MBProgressHUD_JChat.show(text: "好友请求发送失败", view: weakSelf.view, 1)
                    }
                }
                break
                
            case .failure(_):
                DispatchQueue.main.sync {
                    MBProgressHUD_JChat.show(text: "好友请求发送失败", view: weakSelf.view, 1)
                }
                break
            }
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.numberView.textField.resignFirstResponder()
    }
    
    
    //MARK: - click func
    @objc func _addFriend() {
        guard let userName = userName else {
            return
        }
        
        let currentUser = JMSGUser.myInfo()
        if currentUser.username.isEmpty {
            NotificationCenter.default.post(name: GlobalNotificationName.homeInteractionAddFriend.name, object: nil, userInfo: nil)
            return
        }
        
        JMSGFriendManager.sendInvitationRequest(withUsername: userName, appKey: nil, reason: invitationMessageView.text) { (result, error) in
            if error == nil {
                let currentUser = JMSGUser.myInfo()
                let info = JCVerificationInfo.create(username: userName, nickname: self.nickName, appkey: currentUser.appKey!, resaon: self.invitationMessageView.text, state: JCVerificationType.wait.rawValue, initiator: currentUser.username, type: .single, eventId: "")
                JCVerificationInfoDB.shareInstance.insertData(info)
                NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
                //MBProgressHUD_JChat.show(text: "好友请求已发送, 等待对方通过验证", view: self.view, 2)
//                weak var weakSelf = self
//                let time: TimeInterval = 2
//                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
//                    weakSelf?.navigationController?.popViewController(animated: true)
//                }
                let dict: [String: Any] = ["isSuccess": error == nil]
                NotificationCenter.default.post(name: GlobalNotificationName.homeInteractionAddFriend.name, object: nil, userInfo: dict)
            }
//            else {
//                if let er = error as NSError?, er.code == 805002 {
//                    MBProgressHUD_JChat.show(text: "对方已经是你的好友", view: self.view, 2)
//                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
//                        self.navigationController?.popViewController(animated: true)
//                    }
//                }
//            }
        }
    }
}


extension MTAddFriendViewController {

    override func yp_navigationBarTintColor() -> UIColor! {
        return UIColor(hex: 0xFFFFFF)
    }

    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .styleBlack, .backgroundStyleOpaque]
    }

    override func yp_navigationBackgroundColor() -> UIColor! {
        return UIColor(hex: 0x000000)
    }
}
